const { src, dest, watch, series, parallel } = require('gulp');

const htmlMin = require('gulp-htmlmin'); // 压缩html
const babel = require('gulp-babel');
const terser = require('gulp-terser'); // 压缩js
const less = require('gulp-less'); // npm i gulp-less会自动帮我们安装less
const postcss = require('gulp-postcss'); // 兼容浏览器的前缀  npm i gulp-postcss这个并没有帮安装postcss，需手动安装一下
const postcssPresetEnv = require('postcss-preset-env'); 
const inject = require('gulp-inject'); // 注入到html文件里 

const browserSync = require('browser-sync'); // 搭建本地服务

const del = require('del');

const htmlTask = () => {
  return src("./src/*.html", {base: "./src"}) // {base: "./src"} 按./src下面的路径层级来输出文件
    .pipe(htmlMin({
      collapseWhitespace: true // 折叠空白行
    }))
    .pipe(dest("./dist"))
}

const jsTask = () => {
  return src("./src/js/**.js", {base: "./src"})
    .pipe(babel({presets: ["@babel/preset-env"]}))
    .pipe(terser({mangle: {toplevel: true}}))
    .pipe(dest("./dist"))
}

const lessTask = () => {
  return src("./src/css/*.less", {base: "./src"})
    .pipe(less())
    .pipe(postcss([postcssPresetEnv()]))
    .pipe(dest("./dist"))
}

const injectHtml = () => {
  return src("./dist/*.html")
    .pipe(inject(src(["./dist/js/*.js", "./dist/css/*.css"]), {relative: true})) // {relative: true} inject插件的第二哥参数options可进行配置，相对路径
    .pipe(dest('./dist'))
}

// 搭建本地服务器
const bs = browserSync.create();
const serve = () => {
  watch("./src/*.html", series(htmlTask, injectHtml));
  watch("./src/js/*.js", series(jsTask, injectHtml));
  watch("./src/css/*.less", series(jsTask, lessTask));

  bs.init({
    port: 8080,
    open: true,
    files: "./dist/*", 
    server: {
      baseDir: "./dist"
    }
  })
}

const clean = () => {
  return del(["dist"])
}

const buildTask = series(clean, parallel(htmlTask, jsTask, lessTask), injectHtml);
const serveTask = series(buildTask, serve);

module.exports = {
  serveTask,
  buildTask
}
// npx gulp foo 这里npx会自动到.bin下面找到gulp，执行foo任务，这里并没有指定文件，是默认找gulpfile.js，看看gulpfile.js里导出了什么任务，就执行什么任务
// gulp 是不支持模块化的，但是可以用一个包bower来支持模块化，但是gulp bower这俩东西没有关联性的